from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 直接写明MySQL连接参数
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:Zktw%402025@111.198.53.163:58842/twrpa"

# 创建数据库引擎
engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    pool_pre_ping=True,
    pool_recycle=1800,  # 30分钟回收连接
    pool_size=20,       # 连接池大小
    max_overflow=30,    # 最大溢出连接数
    pool_timeout=30,    # 连接池超时时间
    connect_args={
        "connect_timeout": 60,      # 连接超时时间
        "read_timeout": 60,         # 读取超时时间
        "write_timeout": 60,        # 写入超时时间
        "charset": "utf8mb4",
        "autocommit": False,
        "sql_mode": "STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO"
    }
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基类
Base = declarative_base()

# 获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close() 